package com.letoken.platform.app.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.util.HttpClientUtil;
import com.letoken.platform.repo.app.dto.ImUserLoginDto;
import com.letoken.platform.repo.app.dto.UpdateImUserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wyl
 * @Description 发起im服务器的http请求
 * @date 2023/2/8 17:21
 * @Version 1.0
 */
@Slf4j
@Component
public class ImHttpUtil {
    private static String imHost;

    @Value("${im.host}")
    private String imHostValue;

    @PostConstruct
    public void init() {
        imHost = imHostValue;
    }

    public static void imLogin(ImUserLoginDto dto) {
        HashMap<String, Object> params = new HashMap<>();

        try {
            params.put("clientId", dto.getDeviceId());
            params.put("platform", dto.getPlatform());
            params.put("letokenToken", dto.getLetokenToken());
            String json = JSONObject.toJSONString(params);
            String res;

            String url = imHost + "/login_wallet_address";
            res = HttpClientUtil.sendPostJson(url, json, null);
            JSONObject jsonObject = JSONObject.parseObject(res);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                log.info("用户：" + dto.getUserId() + " 登录im成功！");
            }
        } catch (Exception e) {
            log.error("imLogin error！[{}] [{}] [{}]", dto.getUserId(), dto.getDeviceId(), e.getMessage());
        }
    }

    public static void updateUserInfo(String token, Integer userId, UpdateImUserInfoDto dto) {
        String json = JSONObject.toJSONString(dto);
        String res;
        try {
            String url = imHost + "/update_user_info";
            Map<String, String> header = new HashMap<>();
            header.put("letokenToken",token);
            header.put("letokenUserId",userId.toString());
            res = HttpClientUtil.sendPostJson(url, json, header);
            JSONObject jsonObject  = JSONObject.parseObject(res);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                log.info("用户：" + dto.getUserId() + " 修改信息成功！");
            } else {
                log.error("code = " + code + "  用户：" + dto.getUserId() + " 修改用户信息失败！");
                throw new RuntimeException("修改用户信息失败");
            }
        } catch (Exception e) {
            log.error(MessageFormat.format("修改用户信息失败 用户id：{0},异常信息：{1}", userId,e.getLocalizedMessage()));
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_WALLET_TX_001);

        }
    }
}
